<script setup>
import List from '../components/List.vue'
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getIngressListHandler as getListHandler, getIngressTopologyHandler as getTopology, deleteIngressHandler as deleteHandler } from '../../api/ingress.js'
import { ref, toRefs, reactive, computed } from 'vue'
import DialogYaml from '../components/DialogYaml.vue' // codeMirror 从DialogYaml组件引用
import { obj2Yaml } from '../../utils/utils'
import GenericOptions from '../components/GenericOptions.vue'
import { DataSet,Network } from 'vis-network/standalone'

const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  topIngressName: "",
  deleteItem: "",
  yamlContent: "",
  
})

// 定义查询pod列表函数
const getList = () => {
  getListHandler({clusterId: data.clusterId, namespace: data.namespace}).then(
    (res) => {
      data.items = res.data.data.items
      console.log("Ingress列表",data.items)
    }
  )
}

// 回调函数传给ClusterNamespaceSelector组件
const rollback = (clusterId,namespace) => {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}
const search = ref('')
const filterTableData = computed(() =>
  data.items.filter(
    (item) =>
      !search.value ||
      item.metadata.name.toLowerCase().includes(search.value.toLowerCase())
  )
)

const showDetail = ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  const itemtemp = { // yaml补上apiVersion字段
    "apiVersion": "networking.k8s.io/v1",
    "kind": "Ingress",
    "metadata": item.metadata,
    "spec": item.spec
  }
  const yamlData = obj2Yaml(itemtemp) // 当前数据转成yaml
  data.yamlContent = yamlData
  showDetail.value = true

}

let showTop = ref(false)
const showTopology = async (row) => {
  showTop.value = true
  data.topIngressName = row.metadata.name
  var nodes = null
  var edges = null
  await getTopology({clusterId: data.clusterId, namespace: data.namespace,name: row.metadata.name}).then((res) => {
    nodes = res.data.data.nodes
    edges = res.data.data.edges
    console.log("items:", {"nodes": nodes, "edges": edges})
  })
  var container = document.getElementById("mynetwork");
  var visdata = {
    nodes: nodes,
    edges: edges,
  };
  var options = {
    edges: {
      //箭头
      arrows: {
        to: {
          enabled: true,
        }
      },
      color: {
        color: "#8488A2"
      },
      dashes: true,  //虚线
    },
    nodes: {
      //阴影
      // shadow: true
      color:{
        border: '#281B13',
        background: '#CA8650'
      }
    },
    layout: {
      hierarchical: { // 定义层次结构
        direction: "UD",
        sortMethod: "directed",
        levelSeparation: 120,
      }
    }
  };
  var network = new Network(container, visdata, options);
}
const { yamlContent, clusterId, namespace, topIngressName } = toRefs(data)
const handlerChange = (value) => {
  console.log(value)
}
</script>

<template>
  <List title="Ingress列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">
      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
    </template>
    <template #main>
      <el-table
      border
      height="480"
      :data="filterTableData"
      style="width: 100%"
      :default-sort="{prop:'metadata.creationTimestamp',order:'descending'}"
      >
        <el-table-column fixed prop="" align="center" label="名称">
          <template #default="scope">
            <el-button link type="primary" @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="spec.ingressClassName" align="center" label="IngressClass名称" width="240"/>
        <el-table-column prop="spec.ports" align="center" label="域名和路径" width="360">
          <template #default="scope">
            <!-- 拿到rules下的http路由配置 -->
            <template v-for="rule in scope.row.spec.rules">
              <!-- 拿到paths下的路径配置 -->
              <span style="display: block;" v-for="path in rule.http.paths">
                {{ rule.host }}{{ path.path }}
              </span>
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="120" />
        <el-table-column fixed="right" align="center" label="操作" width="320" >
          <template #default="scope">
            <GenericOptions
            v-on:delete-rollback="getList"
            :disabled="scope.row.metadata.deletionTimestamp != undefined"
            resource-type="Ingress"
            :name="scope.row.metadata.name"
            :namespace="scope.row.metadata.namespace"
            :cluster-id="clusterId"
            ></GenericOptions>
            <el-button link type="primary" @click="showTopology(scope.row)">拓扑图</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <DialogYaml
  :cluster-id="data.clusterId"
  :namespace="data.namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => {showDetail = val }"
  >
  </DialogYaml>
  <el-dialog append-to-body width="70%" center draggable v-model="showTop">
      <template #header="{ titleId, titleClass }">
          <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
              <el-tag class="el-tag" size="large" title="集群">{{ clusterId }}</el-tag>>
              <el-tag class="el-tag" size="large" title="命名空间">{{ namespace }}</el-tag>>
              <el-tag class="el-tag" size="large" title="资源名称">{{ topIngressName }}</el-tag>
          </div>
      </template>
      <div id="mynetwork">

      </div>
  </el-dialog>
</template>

<style scoped>
#mynetwork {
  width: 100%;
  height: 400px;
  border: 1px solid lightgray;
}
</style>
